package com.yonyougov.devops.cruxcisupport.k8s;

import com.yonyougov.devops.cruxcisupport.app.AppService;
import com.yonyougov.devops.cruxcisupport.appenv.AppEnvEntity;
import com.yonyougov.devops.cruxcisupport.appenv.AppEnvService;
import com.yonyougov.devops.cruxcisupport.appenv.dto.AppEnvPageLikeDbParams;
import com.yonyougov.devops.cruxcisupport.appenv.vo.AppEnvPageVo;
import com.yonyougov.devops.cruxcisupport.env.EnvService;
import com.yonyougov.devops.cruxcisupport.k8s.deployment.DeploymentRepository;
import com.yonyougov.devops.cruxcisupport.k8s.pod.PodRepository;
import io.fabric8.kubernetes.api.model.apps.Deployment;
import io.fabric8.kubernetes.client.KubernetesClient;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Slf4j
public class K8sTask {
    private final K8sRepository k8sRepository;
    private final PodRepository podRepository;
    private final DeploymentRepository deploymentRepository;
    private AppEnvService appEnvService;

    public K8sTask(AppEnvService appEnvService, PodRepository podRepository, K8sRepository k8sRepository, DeploymentRepository deploymentRepository) {
        this.appEnvService = appEnvService;
        this.podRepository = podRepository;
        this.k8sRepository = k8sRepository;
        this.deploymentRepository = deploymentRepository;
    }

    @SneakyThrows
    public void syncPodStatus(String envName) {
        //初始化k8s客户端
        KubernetesClient client = k8sRepository.createDefaultClient(envName);
        //获取当前用户下部署信息
        AppEnvPageLikeDbParams params = new AppEnvPageLikeDbParams();
        params.setEnvName(envName);
        params.setPageAble(false);
        List<AppEnvPageVo> appEnvPageVos = appEnvService.findAllJoinBy(params);
        for (AppEnvPageVo appEnvPageVo : appEnvPageVos) {
            boolean result = false;
            AppEnvEntity appEnvEntity = new AppEnvEntity();
            String appName = appEnvPageVo.getAppName();
            //获取状态
            List<String> podNames = podRepository.getPodNames(client,envName, appName);
            for (String podName : podNames) {
                result = podRepository.isRunning(client,envName, podName);
            }
            if(result){
                appEnvEntity.setState("正常");
            }else{
                appEnvEntity.setState("不正常");
            }
            //获取实例数
            Deployment deployment = deploymentRepository.get(client, envName, appName);
            if(null == deployment){
                log.error("deployment:{} 不存在！", appName);
                continue;
            }
            Integer replicas = deployment.getSpec().getReplicas();
            appEnvEntity.setReplicas(replicas);
            //更新数据库
            appEnvEntity.setId(appEnvPageVo.getId());
            appEnvService.update(appEnvEntity);
        }
    }
}
